/**
 * 严肃声明：
 * 开源版本请务必保留此注释头信息，若删除我方将保留所有法律责任追究！
 * 本软件已申请软件著作权，受国家版权局知识产权以及国家计算机软件著作权保护！
 * 可正常分享和学习源码，不得用于违法犯罪活动，违者必究！
 * Copyright (c) 2019-2021 十三 all rights reserved.
 * 版权所有，侵权必究！
 */
package ltd.newbee.mall.service.impl;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.alibaba.fastjson.TypeReference;
import lombok.extern.slf4j.Slf4j;
import ltd.newbee.mall.api.admin.param.BatchIdSendParam;
import ltd.newbee.mall.api.mall.param.*;
import ltd.newbee.mall.api.mall.vo.*;
import ltd.newbee.mall.common.*;
import ltd.newbee.mall.dao.*;
import ltd.newbee.mall.entity.*;
import ltd.newbee.mall.service.AccessTokenService;
import ltd.newbee.mall.service.NewBeeMallOrderService;
import ltd.newbee.mall.util.*;
import ma.glasnost.orika.MapperFacade;
import nuonuo.open.sdk.NNOpenSDK;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.CollectionUtils;
import org.springframework.util.StringUtils;

import javax.annotation.Resource;
import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletResponse;
import java.math.BigDecimal;
import java.net.URLEncoder;
import java.text.SimpleDateFormat;
import java.util.*;
import java.util.function.Function;
import java.util.stream.Collectors;

import static java.util.stream.Collectors.groupingBy;

@Service
@Slf4j
public class NewBeeMallOrderServiceImpl implements NewBeeMallOrderService {

    @Autowired
    private NewBeeMallOrderMapper newBeeMallOrderMapper;
    @Autowired
    private NewBeeMallOrderItemMapper newBeeMallOrderItemMapper;
    @Autowired
    private NewBeeMallShoppingCartItemMapper newBeeMallShoppingCartItemMapper;
    @Autowired
    private NewBeeMallGoodsMapper newBeeMallGoodsMapper;
    @Autowired
    private NewBeeMallOrderAddressMapper newBeeMallOrderAddressMapper;

    @Resource
    private PublicPay publicPay;

    @Autowired
    private MapperFacade mapperFacade;

    @Autowired
    private AccessTokenService accessTokenService;
    @Value("${bill.appKey}")
    public String appKey;
    @Value("${bill.appSecret}")
    public String appSecret;
    @Value("${bill.url}")
    public String url;
    @Value("${bill.taxnum}")
    public String taxnum;

    @Value("${bill.salerAccount}")
    public String salerAccount;

    @Value("${deliveryFee}")
    public String deliveryFee;

    @Value("${bill.salerTel}")
    public String salerTel;

    @Value("${bill.salerAddress}")
    public String salerAddress;

    @Value("${bill.clerk}")
    public String clerk;

    @Value("${bill.taxRate}")
    public String taxRate;

    @Value("${bill.goodsCode}")
    public String goodsCode;


    @Override
    public NewBeeMallOrderDetailVO getOrderDetailByOrderId(Long orderId) {
        NewBeeMallOrder newBeeMallOrder = newBeeMallOrderMapper.selectByPrimaryKey(orderId);
        if (newBeeMallOrder == null) {
            NewBeeMallException.fail(ServiceResultEnum.DATA_NOT_EXIST.getResult());
        }
        List<NewBeeMallOrderItem> orderItems = newBeeMallOrderItemMapper.selectByOrderId(newBeeMallOrder.getOrderId());
        //获取订单项数据
        if (!CollectionUtils.isEmpty(orderItems)) {
            List<NewBeeMallOrderItemVO> newBeeMallOrderItemVOS = BeanUtil.copyList(orderItems, NewBeeMallOrderItemVO.class);
            NewBeeMallOrderDetailVO newBeeMallOrderDetailVO = new NewBeeMallOrderDetailVO();
            BeanUtil.copyProperties(newBeeMallOrder, newBeeMallOrderDetailVO);
            newBeeMallOrderDetailVO.setOrderStatusString(NewBeeMallOrderStatusEnum.getNewBeeMallOrderStatusEnumByStatus(newBeeMallOrderDetailVO.getOrderStatus()).getName());
            newBeeMallOrderDetailVO.setPayTypeString(PayTypeEnum.getPayTypeEnumByType(newBeeMallOrderDetailVO.getPayType()).getName());
            newBeeMallOrderDetailVO.setNewBeeMallOrderItemVOS(newBeeMallOrderItemVOS);

            // 设置配送相关字段
            newBeeMallOrderDetailVO.setDeliveryType(newBeeMallOrder.getDeliveryType());
            newBeeMallOrderDetailVO.setDeliveryFee(newBeeMallOrder.getDeliveryFee());
            newBeeMallOrderDetailVO.setPickupAddress(newBeeMallOrder.getPickupAddress());

            // 计算商品金额
            BigDecimal goodsAmount = calculateGoodsAmount(newBeeMallOrder);
            newBeeMallOrderDetailVO.setGoodsAmount(goodsAmount);
            return newBeeMallOrderDetailVO;
        } else {
            NewBeeMallException.fail(ServiceResultEnum.ORDER_ITEM_NULL_ERROR.getResult());
            return null;
        }
    }
    @Override
    public NewBeeMallOrderDetailVO getOrderDetailByOrderNo(String orderNo, Long userId) {
        NewBeeMallOrder newBeeMallOrder = newBeeMallOrderMapper.selectByOrderNo(orderNo);
        if (newBeeMallOrder == null) {
            NewBeeMallException.fail(ServiceResultEnum.DATA_NOT_EXIST.getResult());
        }
        if (!userId.equals(newBeeMallOrder.getUserId())) {
            NewBeeMallException.fail(ServiceResultEnum.REQUEST_FORBIDEN_ERROR.getResult());
        }
        List<NewBeeMallOrderItem> orderItems = newBeeMallOrderItemMapper.selectByOrderId(newBeeMallOrder.getOrderId());
        //获取订单项数据
        if (CollectionUtils.isEmpty(orderItems)) {
            NewBeeMallException.fail(ServiceResultEnum.ORDER_ITEM_NOT_EXIST_ERROR.getResult());
        }
        List<NewBeeMallOrderItemVO> newBeeMallOrderItemVOS = BeanUtil.copyList(orderItems, NewBeeMallOrderItemVO.class);
        NewBeeMallOrderDetailVO newBeeMallOrderDetailVO = new NewBeeMallOrderDetailVO();
        BeanUtil.copyProperties(newBeeMallOrder, newBeeMallOrderDetailVO);
        newBeeMallOrderDetailVO.setOrderStatusString(NewBeeMallOrderStatusEnum.getNewBeeMallOrderStatusEnumByStatus(newBeeMallOrderDetailVO.getOrderStatus()).getName());
        newBeeMallOrderDetailVO.setPayTypeString(PayTypeEnum.getPayTypeEnumByType(newBeeMallOrderDetailVO.getPayType()).getName());
        newBeeMallOrderDetailVO.setNewBeeMallOrderItemVOS(newBeeMallOrderItemVOS);

        // 设置配送相关字段
        newBeeMallOrderDetailVO.setDeliveryType(newBeeMallOrder.getDeliveryType());
        newBeeMallOrderDetailVO.setDeliveryFee(newBeeMallOrder.getDeliveryFee());
        newBeeMallOrderDetailVO.setPickupAddress(newBeeMallOrder.getPickupAddress());

        // ========== 计算商品金额 ==========
        BigDecimal goodsAmount = calculateGoodsAmount(newBeeMallOrder);
        newBeeMallOrderDetailVO.setGoodsAmount(goodsAmount);
        return newBeeMallOrderDetailVO;
    }

    /**
     * 计算商品金额（总价 - 快递费）
     */
    private BigDecimal calculateGoodsAmount(NewBeeMallOrder order) {
        if (order == null || order.getTotalPrice() == null) {
            return BigDecimal.ZERO;
        }

        BigDecimal totalPrice = order.getTotalPrice();
        BigDecimal deliveryFee = order.getDeliveryFee();

        // 如果快递费为空或为0，直接返回总价
        if (deliveryFee == null || deliveryFee.compareTo(BigDecimal.ZERO) == 0) {
            return totalPrice;
        }

        // 计算商品金额 = 总价 - 快递费
        BigDecimal goodsAmount = totalPrice.subtract(deliveryFee);

        // 确保金额不为负数
        if (goodsAmount.compareTo(BigDecimal.ZERO) < 0) {
            goodsAmount = BigDecimal.ZERO;
        }

        // 设置精度为2位小数
        return goodsAmount.setScale(2, BigDecimal.ROUND_HALF_UP);
    }

    @Override
    public NewBeeMallOrderDetailVO getAdminOrderDetailByOrderNo(String orderNo) {
        NewBeeMallOrder newBeeMallOrder = newBeeMallOrderMapper.selectByOrderNo(orderNo);
        if (newBeeMallOrder == null) {
            NewBeeMallException.fail(ServiceResultEnum.DATA_NOT_EXIST.getResult());
        }
        List<NewBeeMallOrderItem> orderItems = newBeeMallOrderItemMapper.selectByOrderId(newBeeMallOrder.getOrderId());
        //获取订单项数据
        if (CollectionUtils.isEmpty(orderItems)) {
            NewBeeMallException.fail(ServiceResultEnum.ORDER_ITEM_NOT_EXIST_ERROR.getResult());
        }
        List<NewBeeMallOrderItemVO> newBeeMallOrderItemVOS = BeanUtil.copyList(orderItems, NewBeeMallOrderItemVO.class);
        NewBeeMallOrderDetailVO newBeeMallOrderDetailVO = new NewBeeMallOrderDetailVO();
        BeanUtil.copyProperties(newBeeMallOrder, newBeeMallOrderDetailVO);
        newBeeMallOrderDetailVO.setOrderStatusString(NewBeeMallOrderStatusEnum.getNewBeeMallOrderStatusEnumByStatus(newBeeMallOrderDetailVO.getOrderStatus()).getName());
        newBeeMallOrderDetailVO.setPayTypeString(PayTypeEnum.getPayTypeEnumByType(newBeeMallOrderDetailVO.getPayType()).getName());
        newBeeMallOrderDetailVO.setNewBeeMallOrderItemVOS(newBeeMallOrderItemVOS);

        // 设置配送相关字段
        newBeeMallOrderDetailVO.setDeliveryType(newBeeMallOrder.getDeliveryType());
        newBeeMallOrderDetailVO.setDeliveryFee(newBeeMallOrder.getDeliveryFee());
        newBeeMallOrderDetailVO.setPickupAddress(newBeeMallOrder.getPickupAddress());

        // 计算商品金额
        BigDecimal goodsAmount = calculateGoodsAmount(newBeeMallOrder);
        newBeeMallOrderDetailVO.setGoodsAmount(goodsAmount);

        return newBeeMallOrderDetailVO;
    }

    @Override
    public PageResult getMyOrders(PageQueryUtil pageUtil) {
        int total = newBeeMallOrderMapper.getTotalNewBeeMallOrders(pageUtil);
        List<NewBeeMallOrder> newBeeMallOrders = newBeeMallOrderMapper.findNewBeeMallOrderList(pageUtil);
        List<NewBeeMallOrderListVO> orderListVOS = new ArrayList<>();
        if (total > 0) {
            //数据转换 将实体类转成vo
            orderListVOS = BeanUtil.copyList(newBeeMallOrders, NewBeeMallOrderListVO.class);
            //设置订单状态中文显示值
            for (NewBeeMallOrderListVO newBeeMallOrderListVO : orderListVOS) {
                newBeeMallOrderListVO.setOrderStatusString(NewBeeMallOrderStatusEnum.getNewBeeMallOrderStatusEnumByStatus(newBeeMallOrderListVO.getOrderStatus()).getName());
                // 设置配送方式
                NewBeeMallOrder originalOrder = newBeeMallOrders.stream()
                        .filter(order -> order.getOrderId().equals(newBeeMallOrderListVO.getOrderId()))
                        .findFirst()
                        .orElse(null);
                if (originalOrder != null) {
                    newBeeMallOrderListVO.setDeliveryType(originalOrder.getDeliveryType());
                }
            }
            List<Long> orderIds = newBeeMallOrders.stream().map(NewBeeMallOrder::getOrderId).collect(Collectors.toList());
            if (!CollectionUtils.isEmpty(orderIds)) {
                List<NewBeeMallOrderItem> orderItems = newBeeMallOrderItemMapper.selectByOrderIds(orderIds);
                Map<Long, List<NewBeeMallOrderItem>> itemByOrderIdMap = orderItems.stream().collect(groupingBy(NewBeeMallOrderItem::getOrderId));
                for (NewBeeMallOrderListVO newBeeMallOrderListVO : orderListVOS) {
                    //封装每个订单列表对象的订单项数据
                    if (itemByOrderIdMap.containsKey(newBeeMallOrderListVO.getOrderId())) {
                        List<NewBeeMallOrderItem> orderItemListTemp = itemByOrderIdMap.get(newBeeMallOrderListVO.getOrderId());
                        //将NewBeeMallOrderItem对象列表转换成NewBeeMallOrderItemVO对象列表
                        List<NewBeeMallOrderItemVO> newBeeMallOrderItemVOS = BeanUtil.copyList(orderItemListTemp, NewBeeMallOrderItemVO.class);
                        newBeeMallOrderListVO.setNewBeeMallOrderItemVOS(newBeeMallOrderItemVOS);
                    }
                }
            }
        }
        PageResult pageResult = new PageResult(orderListVOS, total, pageUtil.getLimit(), pageUtil.getPage());
        return pageResult;
    }


    @Override
    @Transactional(rollbackFor = Exception.class)
    public void autoCancelOvertimeOrders() {
        log.info("查询超时订单需要自动取消=" + new Date());

        // 查询超过30分钟未支付的订单
        List<Long> overtimeOrderIds = newBeeMallOrderMapper.selectOvertimeOrderIds(
                NewBeeMallOrderStatusEnum.ORDER_PRE_PAY.getOrderStatus(),
                30 // 30分钟
        );

        if (!CollectionUtils.isEmpty(overtimeOrderIds)) {
            log.info("发现{}个超时订单需要自动取消", overtimeOrderIds.size());

            // 批量关闭订单
            int closeResult = newBeeMallOrderMapper.closeOrder(
                    overtimeOrderIds,
                    NewBeeMallOrderStatusEnum.ORDER_CLOSED_BY_EXPIRED.getOrderStatus()
            );

            // 批量恢复库存
            if (closeResult > 0) {
                recoverStockNum(overtimeOrderIds);
                log.info("成功自动取消{}个超时订单", closeResult);
            }
        }
    }


    // 修改您原有的cancelOrder方法，保持一致性
    @Override
    @Transactional(rollbackFor = Exception.class)
    public String cancelOrder(String orderNo, Long userId) {
        NewBeeMallOrder newBeeMallOrder = newBeeMallOrderMapper.selectByOrderNo(orderNo);
        if (newBeeMallOrder == null) {
            return ServiceResultEnum.ORDER_NOT_EXIST_ERROR.getResult();
        }

        //验证是否是当前userId下的订单，否则报错
        if (!userId.equals(newBeeMallOrder.getUserId())) {
            NewBeeMallException.fail(ServiceResultEnum.NO_PERMISSION_ERROR.getResult());
        }

        // 订单状态判断 - 简化判断逻辑
        Integer orderStatus = newBeeMallOrder.getOrderStatus().intValue();
        if (orderStatus >= NewBeeMallOrderStatusEnum.ORDER_SUCCESS.getOrderStatus() ||
                orderStatus == NewBeeMallOrderStatusEnum.ORDER_CLOSED_BY_MALLUSER.getOrderStatus() ||
                orderStatus == NewBeeMallOrderStatusEnum.ORDER_CLOSED_BY_EXPIRED.getOrderStatus() ||
                orderStatus == NewBeeMallOrderStatusEnum.ORDER_CLOSED_BY_JUDGE.getOrderStatus()) {
            return ServiceResultEnum.ORDER_STATUS_ERROR.getResult();
        }

        // 修改订单状态&&恢复库存
        List<Long> orderIds = Collections.singletonList(newBeeMallOrder.getOrderId());
        int closeResult = newBeeMallOrderMapper.closeOrder(
                orderIds,
                NewBeeMallOrderStatusEnum.ORDER_CLOSED_BY_MALLUSER.getOrderStatus()
        );

        if (closeResult > 0 && recoverStockNum(orderIds)) {
            return ServiceResultEnum.SUCCESS.getResult();
        } else {
            throw new NewBeeMallException("取消订单失败");
        }
    }

    @Override
    public String finishOrder(String orderNo, Long userId) {
        NewBeeMallOrder newBeeMallOrder = newBeeMallOrderMapper.selectByOrderNo(orderNo);
        if (newBeeMallOrder != null) {
            //验证是否是当前userId下的订单，否则报错
            if (!userId.equals(newBeeMallOrder.getUserId())) {
                return ServiceResultEnum.NO_PERMISSION_ERROR.getResult();
            }
            //订单状态判断 非出库状态下不进行修改操作
            if (newBeeMallOrder.getOrderStatus().intValue() != NewBeeMallOrderStatusEnum.ORDER_EXPRESS.getOrderStatus()) {
                return ServiceResultEnum.ORDER_STATUS_ERROR.getResult();
            }
            newBeeMallOrder.setOrderStatus((byte) NewBeeMallOrderStatusEnum.ORDER_SUCCESS.getOrderStatus());
            newBeeMallOrder.setUpdateTime(new Date());
            if (newBeeMallOrderMapper.updateByPrimaryKeySelective(newBeeMallOrder) > 0) {
                return ServiceResultEnum.SUCCESS.getResult();
            } else {
                return ServiceResultEnum.DB_ERROR.getResult();
            }
        }
        return ServiceResultEnum.ORDER_NOT_EXIST_ERROR.getResult();
    }

    @Override
    public String paySuccess(String orderNo, int payType) {
        log.info("回调支付接口paySuccess=" + orderNo);
        NewBeeMallOrder newBeeMallOrder = newBeeMallOrderMapper.selectByOrderNo(orderNo);
        if (newBeeMallOrder != null) {
            //订单状态判断 非待支付状态下不进行修改操作
            if (newBeeMallOrder.getOrderStatus().intValue() != NewBeeMallOrderStatusEnum.ORDER_PRE_PAY.getOrderStatus()) {
                return ServiceResultEnum.ORDER_STATUS_ERROR.getResult();
            }
            newBeeMallOrder.setOrderStatus((byte) NewBeeMallOrderStatusEnum.ORDER_PAID.getOrderStatus());
            newBeeMallOrder.setPayType((byte) payType);
            newBeeMallOrder.setPayStatus((byte) PayStatusEnum.PAY_SUCCESS.getPayStatus());
            newBeeMallOrder.setPayTime(new Date());
            newBeeMallOrder.setUpdateTime(new Date());
            if (newBeeMallOrderMapper.updateByPrimaryKeySelective(newBeeMallOrder) > 0) {
                return ServiceResultEnum.SUCCESSPAY.getResult();
            } else {
                return ServiceResultEnum.DB_ERROR.getResult();
            }
        }
        return ServiceResultEnum.ORDER_NOT_EXIST_ERROR.getResult();
    }

    @Override
    @Transactional
    public String saveOrder(MallUser loginMallUser, MallUserAddress address, List<NewBeeMallShoppingCartItemVO> myShoppingCartItems, BigDecimal deliveryFee, Integer deliveryType, String userAddress, String pickupAddress) {
        List<Long> itemIdList = myShoppingCartItems.stream().map(NewBeeMallShoppingCartItemVO::getCartItemId).collect(Collectors.toList());
        List<Long> goodsIds = myShoppingCartItems.stream().map(NewBeeMallShoppingCartItemVO::getGoodsId).collect(Collectors.toList());
        List<NewBeeMallGoods> newBeeMallGoods = newBeeMallGoodsMapper.selectByPrimaryKeys(goodsIds);

        //检查是否包含已下架商品
        List<NewBeeMallGoods> goodsListNotSelling = newBeeMallGoods.stream()
                .filter(newBeeMallGoodsTemp -> newBeeMallGoodsTemp.getGoodsSellStatus() != Constants.SELL_STATUS_UP)
                .collect(Collectors.toList());
        if (!CollectionUtils.isEmpty(goodsListNotSelling)) {
            //goodsListNotSelling 对象非空则表示有下架商品
            NewBeeMallException.fail(goodsListNotSelling.get(0).getGoodsName() + "已下架，无法生成订单");
        }

        Map<Long, NewBeeMallGoods> newBeeMallGoodsMap = newBeeMallGoods.stream().collect(Collectors.toMap(NewBeeMallGoods::getGoodsId, Function.identity(), (entity1, entity2) -> entity1));
        //判断商品库存
        for (NewBeeMallShoppingCartItemVO shoppingCartItemVO : myShoppingCartItems) {
            //查出的商品中不存在购物车中的这条关联商品数据，直接返回错误提醒
            if (!newBeeMallGoodsMap.containsKey(shoppingCartItemVO.getGoodsId())) {
                NewBeeMallException.fail(ServiceResultEnum.SHOPPING_ITEM_ERROR.getResult());
            }
            //存在数量大于库存的情况，直接返回错误提醒
            if (shoppingCartItemVO.getGoodsCount() > newBeeMallGoodsMap.get(shoppingCartItemVO.getGoodsId()).getStockNum()) {
                NewBeeMallException.fail(ServiceResultEnum.SHOPPING_ITEM_COUNT_ERROR.getResult());
            }
        }

        //删除购物项
        if (!CollectionUtils.isEmpty(itemIdList) && !CollectionUtils.isEmpty(goodsIds) && !CollectionUtils.isEmpty(newBeeMallGoods)) {
            if (newBeeMallShoppingCartItemMapper.deleteBatch(itemIdList) > 0) {
                List<StockNumDTO> stockNumDTOS = BeanUtil.copyList(myShoppingCartItems, StockNumDTO.class);
                int updateStockNumResult = newBeeMallGoodsMapper.updateStockNum(stockNumDTOS);
                if (updateStockNumResult < 1) {
                    NewBeeMallException.fail(ServiceResultEnum.SHOPPING_ITEM_COUNT_ERROR.getResult());
                }

                //生成订单号
                String orderNo = NumberUtil.genOrderNo();
                BigDecimal priceTotal = BigDecimal.ZERO;

                //保存订单
                NewBeeMallOrder newBeeMallOrder = new NewBeeMallOrder();
                newBeeMallOrder.setOrderNo(orderNo);
                newBeeMallOrder.setUserId(loginMallUser.getUserId());

                //计算商品总价
                for (NewBeeMallShoppingCartItemVO newBeeMallShoppingCartItemVO : myShoppingCartItems) {
                    BigDecimal baseTotal = newBeeMallShoppingCartItemVO.getSellingPrice().multiply(BigDecimal.valueOf(newBeeMallShoppingCartItemVO.getGoodsCount()));
                    priceTotal = priceTotal.add(baseTotal);
                }

                if (priceTotal.compareTo(BigDecimal.ZERO) <= 0) {
                    NewBeeMallException.fail(ServiceResultEnum.ORDER_PRICE_ERROR.getResult());
                }

                // ========== 修复bug：添加快递费验证逻辑 ==========
                // 验证快递费参数
                if (deliveryFee == null) {
                    deliveryFee = BigDecimal.ZERO;
                    log.info("快递费参数为null，设置为0");
                }

                // 如果是自提方式，强制快递费为0
                if (deliveryType == 1) {
                    deliveryFee = BigDecimal.ZERO;
                    log.info("自提订单，快递费强制设置为0");
                }

                // 确保快递费不为负数
                if (deliveryFee.compareTo(BigDecimal.ZERO) < 0) {
                    deliveryFee = BigDecimal.ZERO;
                    log.info("快递费为负数，强制设置为0");
                }

                // 处理可能的精度问题，保留2位小数
                deliveryFee = deliveryFee.setScale(2, BigDecimal.ROUND_HALF_UP);

                // 记录快递费信息用于调试
                log.info("订单快递费设置 - 配送方式: {}, 快递费: {}, 商品总价: {}",
                        deliveryType, deliveryFee, priceTotal);
                // ========== 修复结束 ==========

                //设置配送方式和快递费
                newBeeMallOrder.setDeliveryType(deliveryType);
                newBeeMallOrder.setDeliveryFee(deliveryFee);
                newBeeMallOrder.setPickupAddress(pickupAddress);

                //计算总价（商品总价 + 快递费）
                BigDecimal totalPrice = priceTotal.add(deliveryFee);
                newBeeMallOrder.setTotalPrice(totalPrice);

                String extraInfo = "";
                newBeeMallOrder.setExtraInfo(extraInfo);

                //生成订单项并保存订单项纪录
                if (newBeeMallOrderMapper.insertSelective(newBeeMallOrder) > 0) {
                    //生成订单收货地址快照，并保存至数据库（只有快递方式才保存详细地址）
                    if (deliveryType == 2 && address != null) {
                        NewBeeMallOrderAddress newBeeMallOrderAddress = new NewBeeMallOrderAddress();
                        BeanUtil.copyProperties(address, newBeeMallOrderAddress);
                        newBeeMallOrderAddress.setOrderId(newBeeMallOrder.getOrderId());
                        newBeeMallOrderAddressMapper.insertSelective(newBeeMallOrderAddress);
                    }

                    //生成所有的订单项快照，并保存至数据库
                    List<NewBeeMallOrderItem> newBeeMallOrderItems = new ArrayList<>();
                    for (NewBeeMallShoppingCartItemVO newBeeMallShoppingCartItemVO : myShoppingCartItems) {
                        NewBeeMallOrderItem newBeeMallOrderItem = new NewBeeMallOrderItem();
                        //使用BeanUtil工具类将newBeeMallShoppingCartItemVO中的属性复制到newBeeMallOrderItem对象中
                        BeanUtil.copyProperties(newBeeMallShoppingCartItemVO, newBeeMallOrderItem);
                        //NewBeeMallOrderMapper文件insert()方法中使用了useGeneratedKeys因此orderId可以获取到
                        newBeeMallOrderItem.setOrderId(newBeeMallOrder.getOrderId());
                        //保存规格数据
                        newBeeMallOrderItem.setSpecData(newBeeMallShoppingCartItemVO.getSpecData());
                        newBeeMallOrderItems.add(newBeeMallOrderItem);
                    }

                    //保存至数据库
                    if (newBeeMallOrderItemMapper.insertBatch(newBeeMallOrderItems) > 0) {
                        //记录最终订单金额信息
                        log.info("订单创建成功 - 订单号: {}, 商品金额: {}, 快递费: {}, 总金额: {}",
                                orderNo, priceTotal, deliveryFee, totalPrice);
                        //所有操作成功后，将订单号返回，以供Controller方法跳转到订单详情
                        return orderNo;
                    }
                    NewBeeMallException.fail(ServiceResultEnum.ORDER_PRICE_ERROR.getResult());
                }
                NewBeeMallException.fail(ServiceResultEnum.DB_ERROR.getResult());
            }
            NewBeeMallException.fail(ServiceResultEnum.DB_ERROR.getResult());
        }
        NewBeeMallException.fail(ServiceResultEnum.SHOPPING_ITEM_ERROR.getResult());
        return ServiceResultEnum.SHOPPING_ITEM_ERROR.getResult();
    }

    @Override
    public PageResult getNewBeeMallOrdersPage(PageQueryUtil pageUtil) {
        List<NewBeeMallOrder> newBeeMallOrders = newBeeMallOrderMapper.findNewBeeMallOrderList(pageUtil);
        int total = newBeeMallOrderMapper.getTotalNewBeeMallOrders(pageUtil);
        PageResult pageResult = new PageResult(newBeeMallOrders, total, pageUtil.getLimit(), pageUtil.getPage());
        return pageResult;
    }


    @Override
    @Transactional
    public String updateOrderInfo(NewBeeMallOrder newBeeMallOrder) {
        NewBeeMallOrder temp = newBeeMallOrderMapper.selectByPrimaryKey(newBeeMallOrder.getOrderId());
        //不为空且orderStatus>=0且状态为出库之前可以修改部分信息
        if (temp != null && temp.getOrderStatus() >= 0 && temp.getOrderStatus() < 3) {
            temp.setTotalPrice(newBeeMallOrder.getTotalPrice());
            temp.setUpdateTime(new Date());
            if (newBeeMallOrderMapper.updateByPrimaryKeySelective(temp) > 0) {
                return ServiceResultEnum.SUCCESS.getResult();
            }
            return ServiceResultEnum.DB_ERROR.getResult();
        }
        return ServiceResultEnum.DATA_NOT_EXIST.getResult();
    }


    @Override
    @Transactional
    public String updateByPrimaryKeySelective(NewBeeMallOrder newBeeMallOrder) {
        //不为空且orderStatus>=0且状态为出库之前可以修改部分信息
        if (newBeeMallOrderMapper.updateByPrimaryKeySelective(newBeeMallOrder) > 0) {
            return ServiceResultEnum.SUCCESS.getResult();
        }
        return ServiceResultEnum.DATA_NOT_EXIST.getResult();
    }

    @Override
    @Transactional
    public String checkDone(Long[] ids) {
        //查询所有的订单 判断状态 修改状态和更新时间
        List<NewBeeMallOrder> orders = newBeeMallOrderMapper.selectByPrimaryKeys(Arrays.asList(ids));
        String errorOrderNos = "";
        if (!CollectionUtils.isEmpty(orders)) {
            for (NewBeeMallOrder newBeeMallOrder : orders) {
                if (newBeeMallOrder.getIsDeleted() == 1) {
                    errorOrderNos += newBeeMallOrder.getOrderNo() + " ";
                    continue;
                }
                if (newBeeMallOrder.getOrderStatus() != 1) {
                    errorOrderNos += newBeeMallOrder.getOrderNo() + " ";
                }
            }
            if (!StringUtils.hasText(errorOrderNos)) {
                //订单状态正常 可以执行配货完成操作 修改订单状态和更新时间
                if (newBeeMallOrderMapper.checkDone(Arrays.asList(ids)) > 0) {
                    return ServiceResultEnum.SUCCESS.getResult();
                } else {
                    return ServiceResultEnum.DB_ERROR.getResult();
                }
            } else {
                //订单此时不可执行出库操作
                if (errorOrderNos.length() > 0 && errorOrderNos.length() < 100) {
                    return errorOrderNos + "订单的状态不是支付成功无法执行出库操作";
                } else {
                    return "你选择了太多状态不是支付成功的订单，无法执行配货完成操作";
                }
            }
        }
        //未查询到数据 返回错误提示
        return ServiceResultEnum.DATA_NOT_EXIST.getResult();
    }

    @Override
    @Transactional
    public String checkOut(BatchIdSendParam batchIdParam) {
        //查询所有的订单 判断状态 修改状态和更新时间
        List<NewBeeMallOrder> orders = newBeeMallOrderMapper.selectByPrimaryKeys(Arrays.asList(batchIdParam.getIds()));
        String errorOrderNos = "";
        if (!CollectionUtils.isEmpty(orders)) {
            for (NewBeeMallOrder newBeeMallOrder : orders) {
                if (newBeeMallOrder.getIsDeleted() == 1) {
                    errorOrderNos += newBeeMallOrder.getOrderNo() + " ";
                    continue;
                }
                if (newBeeMallOrder.getOrderStatus() != 1 && newBeeMallOrder.getOrderStatus() != 2) {
                    errorOrderNos += newBeeMallOrder.getOrderNo() + " ";
                }
            }
            if (!StringUtils.hasText(errorOrderNos)) {
                //订单状态正常 可以执行出库操作 修改订单状态和更新时间
                if (newBeeMallOrderMapper.checkOutAndTracking(batchIdParam.getIds()[0], batchIdParam.getTrackingNo(), batchIdParam.getSendPhone()) > 0) {
                    return ServiceResultEnum.SUCCESS.getResult();
                } else {
                    return ServiceResultEnum.DB_ERROR.getResult();
                }
            } else {
                //订单此时不可执行出库操作
                if (errorOrderNos.length() > 0 && errorOrderNos.length() < 100) {
                    return errorOrderNos + "订单的状态不是支付成功或配货完成无法执行出库操作";
                } else {
                    return "你选择了太多状态不是支付成功或配货完成的订单，无法执行出库操作";
                }
            }
        }
        //未查询到数据 返回错误提示
        return ServiceResultEnum.DATA_NOT_EXIST.getResult();
    }

    @Override
    @Transactional
    public String closeOrder(Long[] ids) {
        //查询所有的订单 判断状态 修改状态和更新时间
        List<NewBeeMallOrder> orders = newBeeMallOrderMapper.selectByPrimaryKeys(Arrays.asList(ids));
        String errorOrderNos = "";
        if (!CollectionUtils.isEmpty(orders)) {
            for (NewBeeMallOrder newBeeMallOrder : orders) {
                // isDeleted=1 一定为已关闭订单
                if (newBeeMallOrder.getIsDeleted() == 1) {
                    errorOrderNos += newBeeMallOrder.getOrderNo() + " ";
                    continue;
                }
                //已关闭或者已完成无法关闭订单
                if (newBeeMallOrder.getOrderStatus() == 4 || newBeeMallOrder.getOrderStatus() < 0) {
                    errorOrderNos += newBeeMallOrder.getOrderNo() + " ";
                }
            }
            if (!StringUtils.hasText(errorOrderNos)) {
                //订单状态正常 可以执行关闭操作 修改订单状态和更新时间&&恢复库存
                if (newBeeMallOrderMapper.closeOrder(Arrays.asList(ids), NewBeeMallOrderStatusEnum.ORDER_CLOSED_BY_JUDGE.getOrderStatus()) > 0 && recoverStockNum(Arrays.asList(ids))) {
                    return ServiceResultEnum.SUCCESS.getResult();
                } else {
                    return ServiceResultEnum.DB_ERROR.getResult();
                }
            } else {
                //订单此时不可执行关闭操作
                if (errorOrderNos.length() > 0 && errorOrderNos.length() < 100) {
                    return errorOrderNos + "订单不能执行关闭操作";
                } else {
                    return "你选择的订单不能执行关闭操作";
                }
            }
        }
        //未查询到数据 返回错误提示
        return ServiceResultEnum.DATA_NOT_EXIST.getResult();
    }

    @Override
    @Transactional
    public String refundOrder(String orderNo) {
        //查询所有的订单 判断状态 修改状态和更新时间
        NewBeeMallOrderDetailVO newBeeMallOrderDetailVO = getAdminOrderDetailByOrderNo(orderNo);

        String refundNo = "103A" + Util.getMerchantOrderId();
        //除了待支付其他的都可以主动退款

        //退款操作
        try {
            String res = publicPay.refund(refundNo, newBeeMallOrderDetailVO);
            JSONObject resObj = JSON.parseObject(res);
            if ("SUCCESS".equals(resObj.getString("errCode"))) {
                //修改订单状态为退款成功
                NewBeeMallOrder newBeeMallOrder = new NewBeeMallOrder();
                newBeeMallOrder.setOrderId(newBeeMallOrderDetailVO.getOrderId());
                newBeeMallOrder.setRefundNo(refundNo);
                //退款成功
                newBeeMallOrder.setRefundStatus("已退款");
                updateByPrimaryKeySelective(newBeeMallOrder);
            }

        } catch (Exception e) {
            return "退款异常=" + e.getMessage();
        }

        //关闭订单(订单状态在1.已支付 2.配货完成 3:出库成功 4.交易成功)
        if (newBeeMallOrderDetailVO.getOrderStatus() > 0) {
            Long[] ids = {newBeeMallOrderDetailVO.getOrderId()};
            String closeRes = closeOrder(ids);
            if (!ServiceResultEnum.SUCCESS.getResult().equals(closeRes)) {
                return closeRes;
            }

        }


        return ServiceResultEnum.SUCCESS.getResult();
    }

    @Override
    @Transactional
    public String refundYwyOrder(String orderNo) {
        //查询所有的订单 判断状态 修改状态和更新时间
        NewBeeMallOrderDetailVO newBeeMallOrderDetailVO = getAdminOrderDetailByOrderNo(orderNo);
        //退款操作
        try {
            //修改订单状态为退款成功
            NewBeeMallOrder newBeeMallOrder = new NewBeeMallOrder();
            newBeeMallOrder.setOrderId(newBeeMallOrderDetailVO.getOrderId());
            //退款成功
            newBeeMallOrder.setRefundStatus("业务员退款通过");
            updateByPrimaryKeySelective(newBeeMallOrder);
        } catch (Exception e) {
            return "退款异常=" + e.getMessage();
        }

        return ServiceResultEnum.SUCCESS.getResult();
    }

    @Override
    public Result newBill(BillInputParam billInputParam) {

        NewBeeMallOrderDetailVO newBeeMallOrderDetailVO = getAdminOrderDetailByOrderNo(billInputParam.getOrderNo());
        NNOpenSDK sdk = NNOpenSDK.getIntance();
        String token = accessTokenService.getMaxAccessToken(sdk); // 访问令牌


        //开具发票
        if (org.apache.commons.lang.StringUtils.isEmpty(newBeeMallOrderDetailVO.getBillNo())) {
            BillParam billParam = mapperFacade.map(billInputParam, BillParam.class);
            // 设置订单基本信息
            billParam.setTerminalNumber("");
            billParam.setListFlag("0");
            billParam.setPushMode("1");
            billParam.setDepartmentId("9F7E9439CA8B4C60A2FFF3EA3290B088");
            billParam.setClerkId("");
            billParam.setRemark("备注信息");
            billParam.setChecker("王五");
            billParam.setPayee("李四");
            billParam.setInvoiceType("1");
            billParam.setInvoiceLine("p");
            billParam.setEmail("test@xx.com");
            billParam.setSalerAccount(salerAccount);
            billParam.setSalerTel(salerTel);
            billParam.setOrderNo(billInputParam.getOrderNo());
            billParam.setCallBackUrl("http:127.0.0.1/invoice/callback/");
            SimpleDateFormat sdf1 = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
            String dateStr1 = sdf1.format(newBeeMallOrderDetailVO.getPayTime());
            billParam.setInvoiceDate(dateStr1);
            billParam.setInvoiceCode("125999915630");
            billParam.setInvoiceNum("00130865");
            billParam.setSalerAddress(salerAddress);
            billParam.setClerk(clerk);
            billParam.setProductOilFlag("0");
            billParam.setExtensionNumber("");
            billParam.setSalerTaxNum(taxnum);
            billParam.setListName("详见销货清单");
            billParam.setProxyInvoiceFlag("0");


            //newBeeMallOrderDetailVO.getNewBeeMallOrderItemVOS()


            // 创建发票明细列表
            List<NewBeeMallOrderItemVO> newBeeMallOrderItemVOS = newBeeMallOrderDetailVO.getNewBeeMallOrderItemVOS();


            List<InvoiceDetail> invoiceDetails = new ArrayList<>();
            for (NewBeeMallOrderItemVO newBeeMallOrderItemVO : newBeeMallOrderItemVOS) {
                // 创建并设置发票明细项
                InvoiceDetail invoiceDetail = new InvoiceDetail();
                JSONObject color = JSON.parseObject(newBeeMallOrderItemVO.getSpecData()).getJSONObject("color");
                String result = color.getString("attrName") + "：" + color.getString("valueName");
                invoiceDetail.setSpecType(result);
                invoiceDetail.setTaxExcludedAmount("");
                invoiceDetail.setInvoiceLineProperty("0");
                invoiceDetail.setFavouredPolicyName("0");
                invoiceDetail.setNum("" + newBeeMallOrderItemVO.getGoodsCount());
                invoiceDetail.setWithTaxFlag("1");
                invoiceDetail.setTax("");
                invoiceDetail.setFavouredPolicyFlag("0");
                invoiceDetail.setTaxRate(taxRate);
                invoiceDetail.setUnit("件");
                invoiceDetail.setDeduction("0");
                invoiceDetail.setPrice(newBeeMallOrderItemVO.getSellingPrice().toString());
                invoiceDetail.setZeroRateFlag("0");
                invoiceDetail.setGoodsCode(goodsCode);
                invoiceDetail.setSelfCode("");
                invoiceDetail.setGoodsName(newBeeMallOrderItemVO.getGoodsName());
                invoiceDetail.setTaxIncludedAmount("");

                // 将明细项添加到列表
                invoiceDetails.add(invoiceDetail);
            }


            // 设置发票明细到订单
            billParam.setInvoiceDetail(invoiceDetails);

            JSONObject jParm = new JSONObject();
            jParm.put("order", billParam);
            String content = JSONObject.toJSONString(jParm);
            log.info("请求开具发票接口<>=" + content);
            log.info("测试请求开票执行=NNOpenSDK");
            String method = "nuonuo.ElectronInvoice.requestBillingNew"; // API方法名
            log.info("请求开具发票接口访问token<>=" + token);
            String senid = UUID.randomUUID().toString().replace("-", ""); // 唯一标识，32位随机码，无需修改，保持默认即可
            String result = sdk.sendPostSyncRequest(url, senid, appKey, appSecret, token, taxnum, method, content);
            log.info("请求开具发票接口返回=" + result);
            RspObjBean rspObjBean = JSON.parseObject(result, new TypeReference<RspObjBean>() {
            });
            if (!"E0000".equals(rspObjBean.getCode())) {
                return ResultGenerator.genFailResult(rspObjBean.getDescribe());
            }

            JSONObject res = JSONObject.parseObject(rspObjBean.getResult().toString());
            NewBeeMallOrder newBeeMallOrder = new NewBeeMallOrder();
            newBeeMallOrder.setOrderId(newBeeMallOrderDetailVO.getOrderId());
            newBeeMallOrder.setBillNo(res.getString("invoiceSerialNum"));
            updateByPrimaryKeySelective(newBeeMallOrder);

            return ResultGenerator.genSuccessResult("发票开具中，请稍后再试");
        } else {
            //开具成功直接查询发票
            if (org.apache.commons.lang.StringUtils.isEmpty(newBeeMallOrderDetailVO.getBillUrl())) {
                //查询开票接口
                String content = "{ \"isOfferInvoiceDetail\": \"1\", \"orderNos\": [], \"serialNos\": [ \"" + newBeeMallOrderDetailVO.getBillNo() + "\" ] }";
                log.info("查询开具发票接口<>=" + content);
                String method = "nuonuo.ElectronInvoice.queryInvoiceResult"; // API方法名
                log.info("查询开具发票接口token<>=" + token);
                String senid = UUID.randomUUID().toString().replace("-", ""); // 唯一标识，32位随机码，无需修改，保持默认即可
                String result = sdk.sendPostSyncRequest(url, senid, appKey, appSecret, token, taxnum, method, content);
                log.info("请求查询发票接口返回=" + result);
                RspObjBean rspObjBean = JSON.parseObject(result, new TypeReference<RspObjBean>() {
                });
                if (!"E0000".equals(rspObjBean.getCode())) {
                    return ResultGenerator.genFailResult(rspObjBean.getDescribe());
                }
                String billUrl = parseInvoiceData(result);
                NewBeeMallOrder newBeeMallOrder = new NewBeeMallOrder();
                newBeeMallOrder.setOrderId(newBeeMallOrderDetailVO.getOrderId());
                newBeeMallOrder.setBillUrl(billUrl);
                updateByPrimaryKeySelective(newBeeMallOrder);
                return ResultGenerator.genSuccessResult(billUrl);
            } else {
                return ResultGenerator.genSuccessResult(newBeeMallOrderDetailVO.getBillUrl());
            }
        }

    }

    @Override
    public Result applyRefund(RefundApplyParam refundApplyParam) {
        NewBeeMallOrder newBeeMallOrder = newBeeMallOrderMapper.selectByOrderNo(refundApplyParam.getOrderNo());
        if (newBeeMallOrder == null) {
            return ResultGenerator.genFailResult("不存在该订单信息");
        }
        NewBeeMallOrder newBeeMallOrderUpdate = new NewBeeMallOrder();
        newBeeMallOrderUpdate.setOrderId(newBeeMallOrder.getOrderId());
        newBeeMallOrderUpdate.setRefundStatus(refundApplyParam.getRefundStatus());
        newBeeMallOrderUpdate.setRefundReason(refundApplyParam.getRefundReason());
        updateByPrimaryKeySelective(newBeeMallOrderUpdate);
        return ResultGenerator.genSuccessResult();
    }

    @Override
    public Result approveInvoice(InvoiceApplyParam refundApplyParam) {
        NewBeeMallOrder newBeeMallOrder = newBeeMallOrderMapper.selectByOrderNo(refundApplyParam.getOrderNo());
        if (newBeeMallOrder == null) {
            return ResultGenerator.genFailResult("不存在该订单信息");
        }
        NewBeeMallOrder newBeeMallOrderUpdate = new NewBeeMallOrder();
        newBeeMallOrderUpdate.setOrderId(newBeeMallOrder.getOrderId());
        newBeeMallOrderUpdate.setIsBill("3");
        updateByPrimaryKeySelective(newBeeMallOrderUpdate);
        return ResultGenerator.genSuccessResult();
    }

    @Override
    public Result applyInvoice(InvoiceApplyParam invoiceApplyParam) {
        NewBeeMallOrder newBeeMallOrder = newBeeMallOrderMapper.selectByOrderNo(invoiceApplyParam.getOrderNo());
        if (newBeeMallOrder == null) {
            return ResultGenerator.genFailResult("不存在该订单信息");
        }
        NewBeeMallOrder newBeeMallOrderUpdate = new NewBeeMallOrder();
        newBeeMallOrderUpdate.setOrderId(newBeeMallOrder.getOrderId());
        newBeeMallOrderUpdate.setIsBill("2");//用户申请开票中
        updateByPrimaryKeySelective(newBeeMallOrderUpdate);
        return ResultGenerator.genSuccessResult();
    }

    @Override
    public Result selectBill(String orderNo) {

        NewBeeMallOrderDetailVO newBeeMallOrderDetailVO = getAdminOrderDetailByOrderNo(orderNo);
        if (org.apache.commons.lang.StringUtils.isNotEmpty(newBeeMallOrderDetailVO.getBillUrl())) {
            return ResultGenerator.genSuccessResult(newBeeMallOrderDetailVO.getBillUrl());
        }
        NNOpenSDK sdk = NNOpenSDK.getIntance();
        String token = accessTokenService.getMaxAccessToken(sdk); // 访问令牌
        //查询开票接口
        String content = "{ \"isOfferInvoiceDetail\": \"1\", \"orderNos\": [], \"serialNos\": [ \"" + newBeeMallOrderDetailVO.getBillNo() + "\" ] }";
        log.info("查询开具发票接口<>=" + content);
        String method = "nuonuo.ElectronInvoice.queryInvoiceResult"; // API方法名
        log.info("查询开具发票接口token<>=" + token);
        String senid = UUID.randomUUID().toString().replace("-", ""); // 唯一标识，32位随机码，无需修改，保持默认即可
        String result = sdk.sendPostSyncRequest(url, senid, appKey, appSecret, token, taxnum, method, content);
        log.info("请求查询发票接口返回=" + result);
        RspObjBean rspObjBean = JSON.parseObject(result, new TypeReference<RspObjBean>() {
        });
        if (!"E0000".equals(rspObjBean.getCode())) {
            return ResultGenerator.genFailResult(rspObjBean.getDescribe());
        }
        String billUrl = parseInvoiceData(result);
        NewBeeMallOrder newBeeMallOrder = new NewBeeMallOrder();
        newBeeMallOrder.setOrderId(newBeeMallOrderDetailVO.getOrderId());
        newBeeMallOrder.setBillUrl(billUrl);
        updateByPrimaryKeySelective(newBeeMallOrder);
        return ResultGenerator.genSuccessResult(billUrl);

    }


    public static String parseInvoiceData(String jsonString) {
        try {
            JSONObject jsonObject = JSONObject.parseObject(jsonString);

            // 判断code是否为E0000
            String code = jsonObject.getString("code");
            if (!"E0000".equals(code)) {
                System.out.println("错误代码: " + code + ", 描述: " + jsonObject.getString("describe"));
                return null;
            }

            // 获取result数组
            JSONArray resultArray = jsonObject.getJSONArray("result");
            if (resultArray.size() > 0) {
                JSONObject firstResult = resultArray.getJSONObject(0);
                String pdfUrl = firstResult.getString("pdfUrl");
                return pdfUrl;
            }

        } catch (Exception e) {
            e.printStackTrace();
        }
        return null;
    }


    @Override
    public List<NewBeeMallOrderItemVO> getOrderItems(Long orderId) {
        NewBeeMallOrder newBeeMallOrder = newBeeMallOrderMapper.selectByPrimaryKey(orderId);
        if (newBeeMallOrder != null) {
            List<NewBeeMallOrderItem> orderItems = newBeeMallOrderItemMapper.selectByOrderId(newBeeMallOrder.getOrderId());
            //获取订单项数据
            if (!CollectionUtils.isEmpty(orderItems)) {
                List<NewBeeMallOrderItemVO> newBeeMallOrderItemVOS = BeanUtil.copyList(orderItems, NewBeeMallOrderItemVO.class);
                return newBeeMallOrderItemVOS;
            }
        }
        return null;
    }

    /**
     * 恢复库存
     *
     * @param orderIds
     * @return
     */
    public Boolean recoverStockNum(List<Long> orderIds) {
        // 查询对应的订单项
        List<NewBeeMallOrderItem> newBeeMallOrderItems = newBeeMallOrderItemMapper.selectByOrderIds(orderIds);

        if (CollectionUtils.isEmpty(newBeeMallOrderItems)) {
            NewBeeMallException.fail("未找到对应的订单项");
            return false;
        }

        // 查询商品当前版本号
        List<Long> goodsIds = newBeeMallOrderItems.stream()
                .map(NewBeeMallOrderItem::getGoodsId)
                .distinct()
                .collect(Collectors.toList());


        List<NewBeeMallGoods> goodsList = newBeeMallGoodsMapper.selectByPrimaryKeys(goodsIds);
        Map<Long, Integer> goodsVersionMap = goodsList.stream()
                .collect(Collectors.toMap(NewBeeMallGoods::getGoodsId, NewBeeMallGoods::getVersion));

        // 构建StockNumDTO，包含版本号
        List<StockNumDTO> stockNumDTOS = new ArrayList<>();
        for (NewBeeMallOrderItem item : newBeeMallOrderItems) {
            StockNumDTO dto = new StockNumDTO();
            dto.setGoodsId(item.getGoodsId());
            dto.setGoodsCount(item.getGoodsCount());
            dto.setVersion(goodsVersionMap.get(item.getGoodsId()));
            stockNumDTOS.add(dto);
        }

        // 执行恢复库存的操作
        int updateStockNumResult = newBeeMallGoodsMapper.recoverStockNum(stockNumDTOS);

        if (updateStockNumResult < 1) {
            NewBeeMallException.fail(ServiceResultEnum.CLOSE_ORDER_ERROR.getResult());
            return false;
        } else {
            return true;
        }
    }
}
